package com.hcb.tonguetiphealth.adapter;

import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader.ImageCallBack;
import com.hcb.tonguetiphealth.model.HealthShare;
import com.hcb.tonguetiphealth.model.ResDish;
import com.hcb.tonguetiphealth.model.Restaurant;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.view.MemberHomepageActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.healthShare.HealthShareInfoWidget;

public class HealthShareListAdapter extends BaseAdapter {

	private Context mContext;
	private List<HealthShare> mList;
	private LayoutInflater vi;
	private AsyncBitmapLoader asyncBitmapLoader;
	private Activity ctx;
	private Map<Object, Spanned>spMap = new HashMap<Object, Spanned>();
	private String keyword;
	
	//无奈之举;将每个展示商家、菜品信息的texttview的可见性保存下来；true,表示可见
	private Map<String, Boolean>tvVisibilityMap = new HashMap<String, Boolean>();
	
	
	public HealthShareListAdapter(Context context,List<HealthShare> list) {
		mContext = context;
		ctx = (Activity)context;
		mList = list;
		asyncBitmapLoader = AsyncBitmapLoader.getInstance();
	
	}
	
	public int getCount() {
		if(mList == null) {
			return 0;
		}
		return mList.size();
	}
	
	public Object getItem(int position) {
		if(mList == null) {
			return null;
		} else {
			return mList.get(position);
		}
	}
	
	public long getItemId(int position) {
		return position;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {

		View view;
		
		if(convertView == null) {
			vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = (LinearLayout) vi.inflate(R.layout.health_share_list_item, null);
		} else {
			view = convertView;
		}
		FillDataIntoView(view, position);
		
		return view;
	}
	
	/**
	 * 加载图片
	 * @param img
	 * @param imageURL
	 */
	private void loadImg(ImageView img, String imageURL ) {
		
        Bitmap bitmap = asyncBitmapLoader.loadBitmap(img, imageURL, new ImageCallBack() {  
              
            public void imageLoad(ImageView imageView, Bitmap bitmap) {  
                // TODO Auto-generated method stub  
                imageView.setImageBitmap(bitmap);  
            }  
        });  
		if(bitmap == null) {    
			img.setImageResource(R.drawable.ic_launcher);    
		} else {    
		    img.setImageBitmap(bitmap);    
		}
	}
	
	/**
	 * 生成html 
	 * @param name
	 * @param picUrl
	 * @return
	 */
	private String namePicUrlToHtml(String title , String picUrl){
		String html= "";
		html += "<br/>" + title  + "<br/>"+
				"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
				"<img alt=\"\" width=\"675\" height=\"519\" src=" + picUrl+ " /><br/>";
		return html;
	}
	
	/**
	 *将商家图片和菜品份数名称各自导入 
	 * @param res
	 * @param llDishPic
	 * @param dishList
	 */
	private void laodDishPic(final Restaurant res,final List<ResDish> dishList, final int position, final Handler handler){
		
//		//商家名和商家图片 目前是会加载多个其他条目的图片。。。
//		final LinearLayout llLayout = new LinearLayout(view.getContext());
//		final TextView tvResName = new TextView(view.getContext());
//		final ImageView imgRes = new ImageView(view.getContext());
//		llLayout.addView(tvResName, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//		llLayout.addView(imgRes, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) );
//		tvResName.setText(res.getName());
//		tvResName.setTextSize(14);
//		loadImg(imgRes, res.getImgURL());
//		llDishPic.addView(llLayout, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		final Message message = new Message();
		message.what = MessageWhat.SHOW_PROGRESSBAR;
//		message.arg1 = position;
		handler.sendMessage(message);
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String html="";
				//商家名和商家图片
				html += "<br/><span style=\"color: #ff0000;\">" + res.getName() + "<br/>" +
						"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
						"<img alt=\"\" width=\"675\" height=\"519\" src=" + res.getImgURL()+ " /><br/>";
				//
				for (int i = 0; i < dishList.size(); i++) {
					ResDish dish = dishList.get(i);
					String contentInfo = dish.getNum() + "份" +dish.getTitle()+":";
					String picUrl = dish.getDishThumb();
					html += namePicUrlToHtml(contentInfo, picUrl);
				}
				html += "<br/></span>";
			    Spanned sp = Html.fromHtml(html, new Html.ImageGetter() {
					@Override
					public Drawable getDrawable(String source) {
						InputStream is = null;
						try {
							is = (InputStream) new URL(source).getContent();
							Drawable d = Drawable.createFromStream(is, "src");
//							d.setBounds(0, 0, d.getIntrinsicWidth(),
//									d.getIntrinsicHeight());
							d.setBounds(0, 0, 250,//图片宽度、高度设置
									150);
							is.close();
							return d;
						} catch (Exception e) {
							return null;
						}
					}
				}, null);
			    spMap.put(position, sp);//存入map，第二次则不用下载
			    Message message = new Message();
//			    message.arg1 = position;
			    message.what = MessageWhat.CLOSE_PROGRESSBAR;
			    handler.sendMessage(message);
			}
			
		}.start();
	}
	
private void laodDishPic(final String imgPath, final int position, final Handler handler){
		final Message message = new Message();
		message.what = MessageWhat.SHOW_PROGRESSBAR;
		handler.sendMessage(message);
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String html="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
				html +=  "<img alt=\"\" width=\"675\" height=\"519\" src=" + imgPath+ " />";
			    Spanned sp = Html.fromHtml(html, new Html.ImageGetter() {
					@Override
					public Drawable getDrawable(String source) {
						InputStream is = null;
						try {
							is = (InputStream) new URL(source).getContent();
							Drawable d = Drawable.createFromStream(is, "src");
//							d.setBounds(0, 0, d.getIntrinsicWidth(),
//									d.getIntrinsicHeight());
							d.setBounds(0, 0, 250,//图片宽度、高度设置
									150);
							is.close();
							return d;
						} catch (Exception e) {
							return null;
						}
					}
				}, null);
			    spMap.put(position, sp);//存入map，第二次则不用下载
			    Message message = new Message();
			    message.what = MessageWhat.CLOSE_PROGRESSBAR;
			    handler.sendMessage(message);
			}
			
		}.start();
	}
	
	
	private void showProgressBar(LinearLayout llProgressBar){
		if (llProgressBar.getVisibility() == View.GONE || llProgressBar.getVisibility() == View.INVISIBLE) {
			llProgressBar.setVisibility(View.VISIBLE);
		}
	}
	
	private void closeProgressBar(LinearLayout llProgressBar){
			llProgressBar.setVisibility(View.GONE);
	}
	
	private void FillDataIntoView(View view,final int position) {
		final HealthShare healthShare = mList.get(position);

		ImageView img = (ImageView)view.findViewById(R.id.health_share_usr_img);
		TextView tvName = (TextView)view.findViewById(R.id.health_name_tv);
		RatingBar rb = (RatingBar)view.findViewById(R.id.health_share_ratingbar);
		TextView tvContent = (TextView)view.findViewById(R.id.health_share_content_textview);
		TextView tvShareNum = (TextView)view.findViewById(R.id.health_share_num_tv);
		final TextView  tvContentInfo = (TextView)view.findViewById(R.id.health_share_content_info_textview);
//	    final  LinearLayout llDishPics = (LinearLayout)view.findViewById(R.id.health_share_cotent_pic_linearout);
		LinearLayout llContent = (LinearLayout)view.findViewById(R.id.health_share_content_linearout);
		final LinearLayout llProgressBar = (LinearLayout)view.findViewById(R.id.progressbar_linearlayout);
		Button btHealthShare = (Button)view.findViewById(R.id.health_share_share_button);
		final ImageView imgUporDown = (ImageView)view.findViewById(R.id.health_share_content_upordown);
		
		final User user = healthShare.getUser();
		final Restaurant res = healthShare.getRes();
		final List<ResDish> dishList = healthShare.getDishList();
		
		if (tvVisibilityMap.get(position+"")!=null && tvVisibilityMap.get(position+"")) {
			if (spMap.get(position)==null) {
				llProgressBar.setVisibility(View.VISIBLE);
			}else {
				tvContentInfo.setVisibility(View.VISIBLE);
				tvContentInfo.setText(spMap.get(position));
			}
		}else {
			tvContentInfo.setVisibility(View.GONE);
			llProgressBar.setVisibility(View.GONE);
		}
		tvName.setText(user.getUserName());
//		tvContent.setText(healthShare.getContent());
		rb.setRating(user.getLevel());
		tvShareNum.setText("null".equals(user.getCommentNum())?"0":user.getCommentNum());
		String content= "";
		if("1".equals( healthShare.getType() )){
			content = "享友在" +res.getName()+ "消费了美食，请您看看是否健康合理";
			tvContent.setText(content);
		}else {
			content = healthShare.getContent();
			if(keyword!=null){
				//将关键字标红
				content = content.replaceAll(keyword, "<font color=\"#ff0000\">"+keyword+"</font>");
				tvContent.setText(Html.fromHtml(content));
			}else {
				tvContent.setText(content);
			}
			
		}
		
		//每个item定义handler，使得对应进度条
		final Handler handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case MessageWhat.SHOW_PROGRESSBAR:
					showProgressBar(llProgressBar);
					break;
				case MessageWhat.CLOSE_PROGRESSBAR:
					closeProgressBar(llProgressBar);
					tvContentInfo.setText(spMap.get(position));
					tvContentInfo.setVisibility(View.VISIBLE);
					break;
				default:
					break;
				}
			}
		
		};
		img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ctx,MemberHomepageActivity.class);
				 Bundle bundle = new Bundle();
				 bundle.putSerializable("memeber", user);
				 intent.putExtras(bundle);
				 intent.putExtra("fromWidget", "HealthShareListAdapter");
				 ctx.startActivity(intent);
			}
		});
		llContent.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (tvContentInfo.getVisibility() == View.GONE || tvContentInfo.getVisibility() == View.INVISIBLE) {
					if (spMap.get(position)!=null) {
						tvContentInfo.setText(spMap.get(position));
						tvContentInfo.setVisibility(View.VISIBLE);
					}else {
						if ("1".equals( healthShare.getType())) {
							laodDishPic(res , dishList, position, handler);
						}else {
							laodDishPic(healthShare.getDiyImg(), position, handler);	
						}
					}
					imgUporDown.setBackgroundResource(R.drawable.close_more);
					tvVisibilityMap.put(position+"", true);
				}else {
					tvContentInfo.setVisibility(View.GONE);
					tvVisibilityMap.put(position+"", false);
					imgUporDown.setBackgroundResource(R.drawable.open_more);
				}
			}
			
			
		});
		btHealthShare.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("healthShare", healthShare);
				Global.sp = spMap.get(position);
				ctx.getIntent().putExtras(bundle);
				ctx.setContentView(new HealthShareInfoWidget(ctx));
			}
		});
		
		String imageURL = user.getImgUrl();
        Bitmap bitmap = asyncBitmapLoader.loadBitmap(img, imageURL, new ImageCallBack() {  
              
            public void imageLoad(ImageView imageView, Bitmap bitmap) {  
                // TODO Auto-generated method stub  
                imageView.setImageBitmap(bitmap);  
            }  
        });  
		if(bitmap == null) {    
			img.setImageResource(R.drawable.ic_launcher);    
		} else {    
		    img.setImageBitmap(bitmap);    
		}
	    
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	
}
